<?php
// +----------------------------------------------------------------------
// | Yzncms [ 御宅男工作室 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://yzncms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 御宅男 <530765310@qq.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 用户自定义函数库
// +----------------------------------------------------------------------
use EasyWeChat\Factory;
use think\Db;
use think\Image;

function conf($val = "", $vals = "")
{
    return config()[$val][$vals];
}

function responseJson($code = 0, $msg = '', $data = null)
{
    $response = array(
        'code' => $code,
        'data' => $data,
        'msg' => $msg
    );
    exit(json_encode($response));
}

function lmcurl($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FAILONERROR, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    $SSL = substr($url, 0, 8) == "https://" ? true : false;
    if ($SSL) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 检查证书中是否设置域名
    }
    $content = curl_exec($ch);
    curl_close($ch);
    return $content;
}

function msg($code = 0, $msg = "", $data, $count = 1)
{

    $res['code'] = $code;

    $res['msg'] = $msg;

    $res['data'] = $data;

    $res['count'] = $count;

    exit(arj($res));

}

function arj($data, $isformdata = 1)
{
    if ($data == '' || empty($data)) return '';

    // if($isformdata) $data = new_stripslashes($data);

    if (version_compare(PHP_VERSION, '5.3.0', '<')) {
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    } else {
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    }
}

/**
 * 获取微信小程序token
 * @return bool|string
 */
function getAccessToken()
{
    $appid = config('wechat.appID');
    $secret = config('wechat.AppSecret');
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_HEADER, 0);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $res = curl_exec($ch);
    curl_close($ch);
    return $res;
}

function getDistance($from, $to)
{
//
    $lastPos = strrpos($to, ';');
    if ($lastPos !== false) {
        $to = explode(';', $to)[1];
    }
//
    $to = explode(',', $to);

    $from = explode(',', $from);

    $radLat1 = deg2rad(floatval($to[1]));// deg2rad()函数将角度转换为弧度

    $radLat2 = deg2rad(floatval($from[1]));

    $radLng1 = deg2rad(floatval($to[0]));

    $radLng2 = deg2rad(floatval($from[0]));

    $a = $radLat1 - $radLat2;

    $b = $radLng1 - $radLng2;

    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137;

    return round($s, 2);
}

//通过IP获取地址
function getDistrictByIP($ip)
{
    $url = "http://ip-api.com/json/" . $ip;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($response, true);
    if ($data && $data['status'] === 'success') {
        return $data['city']; // 返回区县名
    } else {
        return 'Unknown';
    }
}

//获取订单号
function GetOrderSN($type, $data = array())
{

    if ($type == 1) {


        $city_code = cityCode($data);

        $time = date('ymd');

        $lennum = lennum();

        $ordersn = $time . $city_code . $lennum;

        return $ordersn;
    }

    if ($type == 2) {
        $order_id_main = date('YmdHis') . rand(100000, 999999);
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        $osn = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);
        return $osn;
    }

}

/**
 * 区号
 */

function cityCode($data)
{
    $los = $data['lat'] . ',' . $data['lng'];

    $url = "https://apis.map.qq.com/ws/geocoder/v1/?location=" . $los . "&key=" . config('MapKey') . "&type=json";

    $res = lmcurl($url);

    $city = string2array($res);


    if ($city['status'] != 0) {

        GetOrderSN(1, $data);

    }
    $ad_info = $city['result']['ad_info'];

    $length = strlen($ad_info['phone_area_code']);

    $city_code = $ad_info['phone_area_code'];

    if ($length > 3) {
        $city_code = substr($city_code, 1, 3);
    }

    return $city_code;
}

/**
 * 根据地址返回坐标
 */
function getLWByAddress($address)
{
    $key = config('wechat.geocodeMap_ten');
    $url = 'https://apis.map.qq.com/ws/geocoder/v1?address=' . urlencode($address) . '&key=' . $key;
    $response = file_get_contents($url);
    $jsonResponse = json_decode($response, true);
    if ($jsonResponse['status'] == 0) {
        $address = $jsonResponse['result']['location'];
        $data[] = $address['lng'];
        $data[] = $address['lat'];
        return json_encode(array(
            'code' => 0,
            'data' => $data
        ));
    } else {
        return json_encode(array(
            'code' => -1,
            'data' => $jsonResponse
        ));
    }
}

/**
 * 获取前天时间戳范围默认昨天
 */
function getTimestamp($day = -1)
{
    $data_string = $day . " day";
    $yesterday = date("Y-m-d", strtotime($data_string));

// 昨天开始时间戳
    $yesterdayStartTimestamp = strtotime($yesterday . " 00:00:00");

// 昨天结束时间戳
    $yesterdayEndTimestamp = strtotime($yesterday . " 23:59:59");

    return array(
        0 => $yesterdayStartTimestamp,
        1 => $yesterdayEndTimestamp
    );
}

function objectToArray($object)
{
    $jsonString = json_encode($object);
    $array = json_decode($jsonString, true);

    return $array;
}

//生成小程序二维码
function qrcode($value, $page, $width = 600)
{
    try {
        $config = [
            'app_id' => config('wechat.appID'),
            'secret' => config('wechat.AppSecret'),
        ];
        $app = Factory::miniProgram($config);
        $response = $app->app_code->getUnlimit($value, [
            'page' => $page,
            'width' => $width,
        ]);
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->save(ROOT_PATH . 'public/uploads/drivingcode', 'qrcode' . time());
            return config('wechat.url') . '/uploads/drivingcode/' . $filename;
        }
//        msg(-1, '', $response);
        return $response;
    } catch (\Exception $e) {
//        msg(-1, $e->getMessage(), '');
        return $e->getMessage();
    }
}

function showMsg($status, $message = '', $data = array())
{
    $result = array(
        'status' => $status,
        'message' => $message,
        'data' => $data
    );
    exit(json_encode($result));
}

function formatSizeUnits($bytes)
{
    if ($bytes >= 1073741824) {
        // 大于等于 1 GB
        $bytes = number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        // 大于等于 1 MB
        $bytes = number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        // 大于等于 1 KB
        $bytes = number_format($bytes / 1024, 2) . ' KB';
    } else {
        // 小于 1 KB
        $bytes = $bytes . ' Bytes';
    }
    return $bytes;
}

//1看视频 2兑换 3其他
function addFraction($memberId, $fraction_count = 2, $desc = ' ', $type = 1, $is_count = 1)
{
    $insert_data = array(
        'member_id' => $memberId,
        'create_time' => time(),
        'count' => $fraction_count,
        'desc' => $desc,
        'type' => $type,
        'is_count' => $is_count,
    );
    Db::name('fraction_record')->insertGetId($insert_data);
    if ($is_count == 1) {
        Db::name('member')
            ->where('id', '=', $memberId)
            ->setInc('fraction', $fraction_count);
    } else {
        Db::name('member')
            ->where('id', '=', $memberId)
            ->setDec('fraction', $fraction_count);
    }
}

//获取优惠券
function getCoupons($memberId, $coupon_info, $get_type = 1, $invite_member_id = 0)
{
    $now_time = time();
    $insert_data = array(
        'member_id' => $memberId,
        'coupon_id' => $coupon_info['id'],
        'name' => $coupon_info['name'],
        'value' => $coupon_info['value'],
        'min_amount' => $coupon_info['min_amount'],
        'claimed_time' => $now_time,
        'start_time' => $now_time,
        'create_time' => time(),
        'get_type' => $get_type,
        'invite_member_id' => $invite_member_id,
        'desc' => $coupon_info['desc']
    );
    if ($coupon_info['effect_type'] == 1) {
        $insert_data['end_time'] = $coupon_info['effect_end'];
    } else {
        $insert_data['end_time'] = $now_time + ($coupon_info['effect_day'] * 86400);
    }
    //领取张数
    Db::name('coupons')
        ->where('id', '=', $coupon_info['id'])
        ->setInc('claimed_count');
    //增加会员优惠券
    $result_id = Db::name('member_coupons')->insertGetId($insert_data);
    return $result_id;
}

//通过订单id 获取小店核销获取金额
function getShopMoney($order_data)
{
    $order_goods = Db::name('order_goods')
        ->where('order_id', '=', $order_data['id'])
        ->find();
    $goods_info = Db::name('goods')->find($order_goods['goods_id']);
    $shop_get_money = $order_data['origin_price'] * ($goods_info['shop_return'] / 100);
    return round($shop_get_money, 2);
}

//订单回调
//1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货 7已取消 8待取货 9拼团中 10助力发起
function orderPaySuccess($order_data,$pay_type = 1)
{

//    if ($order_data['status'] != 1) {
//        return 0;
//    }
    $order_update = array(
        'id' => $order_data['id'],
        'status' => 2,
        'pay_time' => time(),
        'pay_status' => 1,
//        'transaction_id' => $message['transaction_id'],
    );

    Db::startTrans();
    try {
        Db::name('order')->update($order_update);
        //
        //库存设置
        setGoodsStockByOrder($order_data);
        //升级是否可发起助力
        upCreateZl($order_data);
        //增加代理奖励 设置助力状态
        if ($order_data['order_type'] == 1) {
            Db::name('bargain_activity')->update([
                'id' => $order_data['bargain_activity_id'],
                'is_order' => 1,
                'bargain_status' => 3,
                'status' => 3,
                'order_no' => $order_data['order_no'],
                'finish_time' => time()
            ]);
            dlReward($order_data);
        }
        Db::commit();
        return 1;
    } catch (\Exception $e) {
        Db::rollback();
        return -1;
    }
}

//自提订单生成 取货码 和扫码

function finishOrder($order_info, $type = 1)
{
    $update_data = array(
        'id' => $order_info['id'],
        'status' => 4,
        'finish_time' => time(),
        'finish_type' => $type,
    );
    //代理奖励到账
    getReward($order_info);
    //获取订单商品
    $order_goods = Db::name('order_goods')->where('order_id', '=', $order_info['id'])->find();
    //进行返现
    //拼团订单返积分 助力订单 且助力完成
    if ($order_info['order_type'] == 1) {
        $bargain_activity = Db::name('bargain_activity')->where([
            'order_no' => $order_info['order_no']
        ])->find();
        $goods_info=Db::name('goods')->find($order_goods['goods_id']);
        //给本人返
//        $per_jf = (int)$order_info['sum_jf'] / ($bargain_activity['bargain_times'] + 1);
        $per_jf = (int)$order_info['sum_jf'] * ($goods_info['fq_rate']/100);
        //参与人返
        $per_sum = (int)$order_info['sum_jf'] * ((100-$goods_info['fq_rate'])/100);
        $per_jf2 = (int)$per_sum / $bargain_activity['bargain_times'];
        if ($per_jf > 0) {
            //todo 返回积分部分 11.12 test
            addGWCoupons2($order_info['member_id'], $per_jf, 1, $order_info['id']);
            Db::name('order')->update([
                'id'=>$order_info['id'],
                'return_coupon'=>$per_jf,
                'return_coupon2'=>$per_jf2
            ]);
        }
        if ($per_jf2>0){
            //给助力人员返
            $bargain_record = Db::name('bargain_record')->where([
                'activity_id' => $bargain_activity['id']
            ])->select();
            foreach ($bargain_record as $k => $v) {
                addGWCoupons2($v['member_id'], $per_jf2, 1, $order_info['id']);
            }
        }
        //todo 助力订单完成返回状态
        Db::name('bargain_activity')->where([
            'order_no','=',$order_info['order_no']
        ])->update([
            'is_f'=>1,
            'f_time'=>time()
        ]);
    }
    Db::name('order')->update($update_data);
    //会员商品返回积分每日领取
    dayJf($order_info);
    //会员分享返回积分
    returnfxOrder($order_info);
}

//order-status 1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货 7已取消 8待取货 9助力中10砍价发起
//order-after 订单退款 status 1待同意 2已同意 3已拒绝 4已发货 5已完成

function tuikuanServerOrder($order_info, $tui_money = 0.00, $is_houtui = 0, $tui_reason = '后台主动退款', $imgs = array())
{
    $update_data = array(
        'id' => $order_info['id'],
        'status' => 6,
        'is_tui' => 1,
        'pay_status' => 2,
        'tui_time' => time(),
        'is_houtui' => $is_houtui,
        'tui_moeny' => $tui_money,
        'tui_before' => $order_info['status'],
    );
    Db::name('order')->update($update_data);
    //返回积分
    if ($order_info['shop_coupon'] > 0) {
        addGWCoupons2($order_info['member_id'], $order_info['shop_coupon'], 1, $order_info['id'], 4);
    }

    $order_after = array(
        'tui_no' => 'cp' . GetOrderSN(2),
        'order_no' => $order_info['order_no'],
        'order_id' => $order_info['id'],
        'status' => 5,
        'create_time' => time(),
        'tui_reason' => $tui_reason,
        'order_pay_money' => $order_info['pay_money'],
        'member_id' => $order_info['member_id'],
        'is_fa' => 0,
        'order_status' => 6,
        'tui_money' => $tui_money,
        'is_finish' => 2,
        'supply_id' => $order_info['supply_id']
    );
    if ($imgs['imgs']) {
        $order_after['imgs'] = implode(',', $imgs);
    }
    $order_after_id = Db::name('order_after')->insertGetId($order_after);
    return $order_after_id;
}

function tuikuanServerOrderAfter($order_after_id, $order_info, $tui_money, $is_houtui = 1)
{
    $update_data = array(
        'id' => $order_info['id'],
        'status' => 6,
        'is_tui' => 1,
        'pay_status' => 2,
        'tui_time' => time(),
        'is_houtui' => $is_houtui,
        'tui_moeny' => $tui_money,
//        'tui_before' => $order_info['status'],
    );
    Db::name('order')->update($update_data);
    //返回积分
    if ($order_info['shop_coupon'] > 0) {
        addGWCoupons2($order_info['member_id'], $order_info['shop_coupon'], 1, $order_info['id'], 4);
    }
    $update_order_after = array(
        'id' => $order_after_id,
        'status' => 5,
        'tui_money' => $tui_money,
        'is_finish' => 2
    );
    Db::name('order_after')->update($update_order_after);
    return $order_after_id;
}

function tuikuanServerOrder2($order_info, $is_houtui = 0, $tui_reason = '后台主动退款', $imgs = array())
{
    $update_data = array(
        'id' => $order_info['id'],
        'status' => 6,
        'tui_before' => $order_info['status'],
        'is_houtui' => $is_houtui,
        'tui_time' => time(),
    );
    Db::name('order')->update($update_data);

    $order_after = array(
        'tui_no' => 'cp' . GetOrderSN(2),
        'order_no' => $order_info['order_no'],
        'order_id' => $order_info['id'],
        'status' => 1,
        'create_time' => time(),
        'tui_reason' => $tui_reason,
        'order_pay_money' => $order_info['pay_money'],
        'member_id' => $order_info['member_id'],
        'order_status' => $order_info['status'],
        'is_fa' => 1,
        'is_finish' => 1,
        'supply_id' => $order_info['supply_id']
    );
    if ($imgs['imgs']) {
        $order_after['imgs'] = implode(',', $imgs);
    }
    $order_after_id = Db::name('order_after')->insertGetId($order_after);
    return $order_after_id;
}

function tui($order_id, $tui_money = 0)
{
    $order_info = Db::name('order')
        ->where('id', $order_id)
        ->find();
    $config = config('wechat.wxpay');
    $app = Factory::payment($config);
    if (!$tui_money) {
        $tui_money = $order_info['pay_money'];
    }
    $res = $app->setSubMerchant($config['sub_mch_id'], $config['sub_appid']);
    $result = $res->refund->byOutTradeNumber($order_info['order_no'], $order_info['order_no'], $order_info['pay_money'] * 100, $tui_money * 100, [
        // 可在此处传入其他参数，详细参数见微信支付文档
        'refund_desc' => '订单退款',
    ]);
//    if ($result['return_code'] != "FAIL") {
//        tuikuanServerOrder($order_info, $order_info['pay_money'], 1);
//    }
    return $result;
}


//==========================================================================================================

//发起拼团支付完成
function PtOrderPaySuccess($order_data, $pay_type = 1)
{
    //1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货
    //7已取消 8待取货 9助力中10砍价发起

    $order_update = array(
        'id' => $order_data['id'],
        'status' => 9,
        'pay_time' => time(),
        'pay_status' => 1,
        'pay_type' => $pay_type,
//        'shop_get_money' => getShopMoney($order_data)
    );

//    if ($pay_type == 2) {
//        $order_update['pay_money'] = 0.00;
//        $order_update['pin_coupon'] = $order_data['order_money'];
//    }
    //创建助力活动
    $group_active_id = addPtActivities($order_data);
    $order_update['activity_id'] = $group_active_id;
    //锁定用户
    //clockMember($order_data['member_id']);
    //升级会员
    //upMemberVip($order_data);
    //如果使用现金支付的话 给返回
//    if ($pay_type == 1) {
//        addPTCoupons($order_data['member_id'], $order_data['order_money'], $order_data['id'], 1, '拼团返卷', $order_data['order_no']);
//    }
    //增加助力记录
    addPtParticipants($order_data, $group_active_id, 1);
    //创建代理奖励
    dlReward($order_data);
    Db::name('order')->update($order_update);
    //库存设置 增加助力数量
    setGoodsStockByOrder($order_data);
    return 1;
}

//参加拼团支付完成
function PtOrderPaySuccess2($order_data)
{
    //1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货 7已取消 8待取货 9助力中 10砍价发起
    $order_update = array(
        'id' => $order_data['id'],
        'status' => 9,
        'pay_time' => time(),
        'pay_status' => 1,
        'shop_get_money' => getShopMoney($order_data)
    );
//    if ($order_data['delive_type'] == 1) {
//        $order_update['status'] = 2;
//    } else {
//        $order_update['status'] = 8;
//    }
    Db::name('order')->update($order_update);
    $group_activities_info = Db::name('group_activities')->find($order_data['activity_id']);
    Db::name('group_activities')->where([
        'id' => $order_data['activity_id']
    ])->setInc('now_num');
    //判断是否最后一个人 设置拼团成功
    if ($group_activities_info['group_num'] - $group_activities_info['now_num'] <= 1) {
        pTFinish($order_data['activity_id']);
    }
    //设置拼团上级 更改用户拼团状态
    setPinUp($order_data);
    //更新是否可以助力
    upCreateZl($order_data);
    //锁定用户
//    clockMember($order_data['member_id']);
    //给参与拼团的人返拼团卷
//    addPTCoupons($order_data['member_id'], $order_data['order_money'], $order_data['id'], 1, '拼团返卷', $order_data['order_no']);
    //给发起人返券
//    returnPTToFQ($order_data);
    //升级会员
//    upMemberVip($order_data);
    //增加记录
    addPtParticipants($order_data, $order_data['activity_id'], 2);
    //创建代理奖励
    dlReward($order_data);
    //拼团AB返钱
//    ptABFan($order_data);
    //拼团团队奖
//    teamMoney2($order_data);
    //库存设置
    setGoodsStockByOrder($order_data);
    return 1;
}

//拼团结束
function pTFinish($group_active_id)
{
    $up_active = array(
        'id' => $group_active_id,
        'status' => 2
    );
    Db::name('group_activities')->update($up_active);
    //根据提货方式生成对应状态 获取没有取消拼团的订单
    $pt_order_list = Db::name('order')->where([
        'activity_id' => $group_active_id,
        'status' => 9,
        'order_type' => 1
    ])->select();

//    $group_activities_info=Db::name('group_activities')->find($group_active_id);
//    $origin_order=Db::name('order')->find($group_activities_info['order_id']);
    //获取商品金额 设置返现积分
//    $origin_order_money=$origin_order['order_money'];
//    $one_yuan_jf = config('site.one_yuan_jf') ? config('site.one_yuan_jf') : 100;
//    $sum_jf=$origin_order_money*$one_yuan_jf;
//    $per_jf=(int)$sum_jf/$group_activities_info['group_num'];

    foreach ($pt_order_list as $k => $v) {
        //1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货
        //7已取消 8待取货 9助力中10砍价发起
        $up_order = array(
            'id' => $v['id'],
            'status' => 2,
            'zl_status' => 2
        );
        //给每个人发积分 助力返积分
//        addGWCoupons2($v['member_id'],$per_jf,1,$v['id']);
        Db::name('order')->update($up_order);
    }

}

//创建拼团活动
function addPtActivities($order_info)
{
    Db::startTrans();
    try {
        $order_goods = Db::name('order_goods')->where('order_id', $order_info['id'])->find();
        $goods_info = Db::name('goods')->find($order_goods['goods_id']);
        $goods_attr_value = Db::name('goods_attr_value')->where([
            'goods_id' => $order_goods['goods_id'],
            'suk' => $order_goods['suk']
        ])->find();
        $insert_data = array(
            'goods_id' => $goods_info['id'],
            //商品价格
            'group_price' => $goods_attr_value['price'],
            'group_num' => $goods_info['pin_num'],
            'now_num' => 1,
            'start_time' => time(),
            'end_time' => time() + (60 * $goods_info['pin_time']),
            'status' => 1,
            'suk' => $goods_attr_value['suk'],
            'member_id' => $order_info['member_id'],
            'order_id' => $order_info['id']
        );
        $active_id = Db::name('group_activities')->insertGetId($insert_data);
        Db::commit();
        return $active_id;
    } catch (\Exception $e) {
        Db::rollback();
        return -1;
    }
}

//加入拼团记录
function addPtParticipants($order_info, $group_active_id, $role)
{
    $insert_data = array(
        'group_active_id' => $group_active_id,
        'member_id' => $order_info['member_id'],
        'order_id' => $order_info['id'],
        'create_time' => time(),
        'role' => $role,
    );
    $id = Db::name('group_participants')->insertGetId($insert_data);
    return $id;

}

//拼团卷修改 1拼团返卷 2发起拼团使用 3转换购物卷 4后台充值 5发起拼团别人参与拼团返卷
// type    1拼团返卷 2拼团使用     3转换购物卷
function addPTCoupons($member_id, $num, $order_id, $type, $desc, $order_no = '')
{
    $insert_data = array(
        'member_id' => $member_id,
        'num' => $num,
        'order_id' => $order_id,
        'type' => $type,
        'desc' => $desc,
        'order_no' => $order_no,
        'create_time' => time()
    );
    Db::name('member')->where(['id' => $member_id])->setInc('coupon2', $num);
    $insert_id = Db::name('member_coupon2')->insertGetId($insert_data);
    return $insert_id;
}

//积分 type 1助力返积分 2订单使用 3提现
function addGWCoupons($member_id, $num, $order_id, $order2_id, $type, $desc)
{
    $insert_data = array(
        'member_id' => $member_id,
        'num' => $num,
        'order_id' => $order_id,
        'order2_id' => $order2_id,
        'type' => $type,
        'desc' => $desc,
        'create_time' => time()
    );
    if ($type == 1) {
        $insert_data['sign_time'] = date('Y-m-d', time());
    }
    Db::name('member')->where(['id' => $member_id])->setInc('coupon1', $num);
    $insert_id = Db::name('member_coupon1')->insertGetId($insert_data);
    return $insert_id;
}

//积分 type 1助力返积分 2订单使用 3提现
function addGWCoupons2($member_id, $num, $is_count, $order_id, $type = 1)
{
    switch ($type) {
        case 1:
            $desc = '助力返积分';
            break;
        case 2:
            $desc = '订单使用';
            break;
        case 3:
            $desc = '提现';
            break;
        case 4:
            $desc = '订单退回';
            break;
        case 5:
            $desc = '购物签到';
            break;
        case 6:
            $desc = '分享赚取积分';
            break;
        default:
            $desc = '助力返积分';
    }
    $insert_data = array(
        'member_id' => $member_id,
        'num' => $num,
        'order_id' => $order_id,
        'is_count' => $is_count,
        'type' => $type,
        'desc' => $desc,
        'create_time' => time()
    );
    if ($is_count == 1) {
        Db::name('member')->where(['id' => $member_id])->setInc('coupon1', $num);
    } else {
        Db::name('member')->where(['id' => $member_id])->setDec('coupon1', $num);
    }
    $insert_id = Db::name('member_coupon1')->insertGetId($insert_data);
    return $insert_id;
}

//库存设置
function setGoodsStockByOrder($order_data)
{
//    $order_goods = Db::name('order_goods')->find($order_data['id']);
    $order_goods = Db::name('order_goods')->find($order_data['id']);
    goodsStock($order_goods['goods_id'], $order_goods['suk'], $order_goods['num']);
    if ($order_data['order_type'] == 1) {
        Db::name('goods')->where([
            'id' => $order_goods['goods_id']
        ])->update([
            'zl_count' => Db::raw('zl_count+' . 1),
        ]);
    }

}

//增加销量 减少库存
function goodsStock($goods_id, $suk, $num)
{
    Db::name('goods_attr_value')->where([
        'goods_id' => $goods_id,
        'suk' => $suk
    ])->update([
        'sale_num' => Db::raw('sale_num+' . $num),
        'stock' => Db::raw('stock-' . $num)
    ]);
    Db::name('goods')->where([
        'id' => $goods_id
    ])->update([
        'sale_num' => Db::raw('sale_num+' . $num),
    ]);
}

function getAddressByLocation2($latitude, $longitude)
{
    $key = config('wechat.geocodeMap_ten');
    $nearby = $latitude . ',' . $longitude;
    $url = 'https://apis.map.qq.com/ws/geocoder/v1?location=' . $nearby . '&key=' . $key . '&get_poi=0';
    $response = file_get_contents($url);

    $jsonResponse = json_decode($response, true);

    if ($jsonResponse['status'] == 0) {
        return json_encode(array(
            'code' => 0,
            'data' => $jsonResponse['result']
        ));
    } else {
        return json_encode(array(
            'code' => -1,
            'data' => $jsonResponse['message']
        ));
    }
}

function getMonthTimestamps($year, $month)
{
    $daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
    $timestamps = [];
    for ($day = 1; $day <= $daysInMonth; $day++) {
        $timestamps[] = strtotime("{$year}-{$month}-{$day}");
    }
    return $timestamps;
}

//判断是否可以参加拼团
function isCanPin($group_activities_id, $member_id)
{
    $group_activities_info = Db::name('group_activities')->find($group_activities_id);
    if (!$group_activities_info) {
        msg(-1, '拼团不存在', '');
    }
    if ($group_activities_info['now_num'] >= $group_activities_info['group_num']) {
        msg(-2, '拼团已完成', '');
    }
    if ($group_activities_info['status'] != 1) {
        msg(-3, '当前拼团已失效', '');
    }
//    $member_info = Db::name('member')->find($member_id);
//    if ($member_info['is_pin'] == 2) {
//        msg(-4, "你已参与拼团", '');
//    }
    $group_participants = Db::name('group_participants')->where([
        'group_active_id' => $group_activities_id,
        'member_id' => $member_id
    ])->find();
    if ($group_participants) {
        msg(-3, '你已参与当前拼团', '');
    }
    $pin_order = Db::name('order')->where([
        'activity_id' => $group_activities_id,
        'pin_sort' => 1,
        'order_type' => 1
    ])->find();
    if (!$pin_order) {
        msg(-3, '订单不存在', '');
    }
}

/**
 * 随机砍价方法
 * @param float $price 商品原价
 * @param float $min_price 砍价最低价
 * @param int $people_num 砍价人数
 * @return array 返回砍价结果数组
 */
function bargain($price, $min_price, $people_num)
{
    // 验证参数
    if ($price <= 0 || $min_price < 0 || $people_num <= 0) {
//        return ['code' => 0, 'msg' => '参数错误'];
        msg(-1, '参数错误', '');
    }

    if ($min_price >= $price) {
        msg(-1, '最低价不能大于等于原价', '');
//        return ['code' => 0, 'msg' => '最低价不能大于等于原价'];
    }

    $total_cut = $price - $min_price; // 总需要砍掉的金额
    $cuts = []; // 存储每次砍价的金额

    // 剩余需要砍掉的金额
    $remaining = $total_cut;

    // 生成砍价金额
    for ($i = 0; $i < $people_num - 1; $i++) {
        // 计算最大可砍金额（保证后面的人至少能砍1分钱）
        $max = $remaining - ($people_num - $i - 1) * 0.01;

        // 随机砍价金额（最小0.01元）
        $cut = mt_rand(1, $max * 100) / 100;

        $cuts[] = $cut;
        $remaining -= $cut;
    }

    // 最后一个人砍掉剩余金额
    $cuts[] = round($remaining, 2);

    // 打乱砍价顺序（可选）
    shuffle($cuts);

    // 计算每次砍价后的价格
    $result = [];
    $current_price = $price;
    foreach ($cuts as $cut) {
        $current_price -= $cut;
        $result[] = [
            'cut_amount' => $cut,
            'current_price' => round($current_price, 2)
        ];
    }
    return $result;
//    return [
//        'code' => 1,
//        'data' => [
//            'original_price' => $price,
//            'min_price' => $min_price,
//            'bargain_list' => $result,
//            'final_price' => round($current_price, 2)
//        ]
//    ];
}

function averageBargain($price, $min_price, $people_num)
{
    // 验证参数
    if ($price <= 0 || $min_price < 0 || $people_num <= 0) {
//        return ['code' => 0, 'msg' => '参数错误'];
        msg(-1, '参数错误', '');
    }

    if ($min_price >= $price) {
        msg(-1, '最低价不能大于等于原价', '');
//        return ['code' => 0, 'msg' => '最低价不能大于等于原价'];
    }

    $total_cut = $price - $min_price; // 总需要砍掉的金额
    $average_cut = round($total_cut / $people_num, 2); // 平均每次砍价金额

    // 处理小数精度问题，确保总和正好等于total_cut
    $cuts = array_fill(0, $people_num, $average_cut);
    $sum = array_sum($cuts);
    $diff = round($total_cut - $sum, 2);

    // 调整差额到最后一个砍价金额上
    if ($diff != 0) {
        $cuts[$people_num - 1] += $diff;
    }

    // 计算每次砍价后的价格
    $result = [];
    $current_price = $price;
    foreach ($cuts as $cut) {
        $current_price -= $cut;
        $result[] = [
            'cut_amount' => round($cut, 2),
            'current_price' => round($current_price, 2)
        ];
    }
    return $result;
//    return [
//        'code' => 1,
//        'data' => [
//            'original_price' => $price,
//            'min_price' => $min_price,
//            'average_cut' => $average_cut,
//            'bargain_list' => $result,
//            'final_price' => round($current_price, 2)
//        ]
//    ];
}

//是否可参加砍价
function isCanBargain($bargain_activity_id, $member_id)
{
    $bargain_activity_info = Db::name('bargain_activity')->find($bargain_activity_id);
    if (!$bargain_activity_info) {
        msg(-1, "助力活动不存在", '');
    }
    if ($bargain_activity_info['status'] != 0) {
        msg(-2, "助力活动已结束", '');
    }
    if ($bargain_activity_info['member_id'] == $member_id) {
        msg(-3, "不能给自己助力", '');
    }
    $bargain_record=Db::name('bargain_record')->where([
        'activity_id'=>$bargain_activity_id,
        'member_id'=>$member_id
    ])->find();
    if ($bargain_record){
        msg(-4, "你已参与助力", '');
    }
//    $member_info = Db::name('member')->find($member_id);
//    if ($member_info['is_bargain'] == 2) {
//        msg(-4, "你已参与助力", '');
//    }
//    $bargain_record = Db::name('bargain_record')->where([
//        'member_id' => $member_id
//    ])->find();
//    if ($bargain_record) {
//        msg(-4, "不可砍价", '');
//    }
}

//进行砍价
function bargainJoin($bargain_activity_id, $member_id)
{
//    $bargain_money = Db::name('bargain_money')->where([
//        ['ba_id', '=', $bargain_activity_id],
//        ['br_id', '=', 0],
//    ])->order('sort asc')->find();
    //插入bargain_record
    $bargain_record_data = array(
        'activity_id' => $bargain_activity_id,
        'member_id' => $member_id,
        'cut_amount' => 0,
//        'current_price' => $bargain_money['current_price'],
        'create_time' => time()
    );
    $bargain_record_id = Db::name('bargain_record')->insertGetId($bargain_record_data);
//    $bargain_record_data['id'] = $bargain_record_id;
//    $update_bargain_money = array(
//        'id' => $bargain_money['id'],
//        'br_id' => $bargain_record_id
//    );
//    Db::name('bargain_money')->update($update_bargain_money);
    //更新bargain_activity
    Db::name('bargain_activity')->where([
        'id' => $bargain_activity_id
    ])->update([
//        'current_price' => Db::raw('current_price-' . $bargain_money['cut_amount']),
        'bargain_times' => Db::raw('bargain_times+1'),
    ]);
    //设置砍价上级
//    setBargainUp($bargain_activity_id, $member_id);
//    clockMember($member_id);
    return $bargain_record_data;
}

//砍价是否完成
function bargainFinish($bargain_activity_id)
{
    $bargain_activity_info = Db::name('bargain_activity')->find($bargain_activity_id);
    if ($bargain_activity_info) {
        if ($bargain_activity_info['bargain_times'] >= $bargain_activity_info['max_bargain_times']) {
            Db::name('bargain_activity')->update([
                'id' => $bargain_activity_id,
                'status' => 1,
                'bargain_status' => 2,
                'success_time' => time()
            ]);
        }
    }
}

//砍价订单支付回调
function bargainOrderSuccess2($order_data)
{
    //更新订单状态
    //更新砍价活动数据
    $order_update = array(
        'id' => $order_data['id'],
        'pay_time' => time(),
        'pay_status' => 1,
        'shop_get_money' => getShopMoney($order_data)
    );
    clockMember($order_data['member_id']);
    if ($order_data['delive_type'] == 1) {
        $order_update['status'] = 2;
    } else {
        $order_update['status'] = 8;
    }
    Db::name('order')->update($order_update);
    Db::name('bargain_activity')->update([
        'id' => $order_data['bargain_activity_id'],
        'is_order' => 1,
        'bargain_status' => 3,
        'status' => 3,
        'order_no' => $order_data['order_no'],
    ]);
    //库存设置
    setGoodsStockByOrder($order_data);
    Db::commit();
    return 1;
}

//获取两点之间的距离 返回为米
function distanceHaversine($lat1, $lon1, $lat2, $lon2)
{
    $earthRadius = 6371; // 地球半径，单位为千米
    $dLat = deg2rad($lat2 - $lat1);
    $dLon = deg2rad($lon2 - $lon1);
    $a = sin($dLat / 2) * sin($dLat / 2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLon / 2) * sin($dLon / 2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
    $distance = $earthRadius * $c;
    return $distance;
}

//verify_type  1扫描核销 2核销码核销
function verifyGoodsOrder($order_id, $verify_type, $shop_id, $write_code_digits)
{
    $order_info = Db::name('order')->find($order_id);
    if (!$order_info) {
        msg(-1, '订单所属不存在', '');
    }
    if ($verify_type == 2 && ($order_info['write_code_digits'] != $write_code_digits)) {
        msg(-1, '数字核销码错误', '');
    }
    if ($order_info['status'] == 4 || $order_info['status'] == 5) {
        msg(-1, '订单已完成', '');
    }
    if ($order_info['status'] != 8) {
        msg(-1, '订单状态不可核销', '');
    }
    //商家核销
    if ($order_info['shop_id'] != $shop_id) {
        msg(-1, '订单不属于此商家', '');
    }
    //1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货
    //7已取消 8待取货 9拼团待完成10砍价发起
    //订单更新
    $update_order = array(
        'id' => $order_id,
        'status' => 4,
        'write_status' => 1,
        'finish_time' => time(),
    );
    $data_num = Db::name('order')->update($update_order);
    if ($order_info['shop_get_money'] > 0) {
        addShopMoney($shop_id, $order_info['shop_get_money'], $order_id, 1, '核销奖励');
    }
    //奖励订单返现
    getReward($order_info);
    addGWCouponsToOrder($order_info);
    return $data_num;
}

//增加店家钱
function addShopMoney($shop_id, $money, $order_id, $type, $desc, $is_count = 1)
{
    $insert_data = array(
        'shop_id' => $shop_id,
        'money' => $money,
        'order_id' => $order_id,
        'type' => $type,
        'desc' => $desc,
        'is_count' => $is_count,
        'create_time' => time()
    );
    Db::name('shop_finance')->insertGetId($insert_data);
    Db::name('shop')->where('id', '=', $shop_id)->setInc('money', $money);
}

function maskString($str)
{
    $trimmed = trim($str);
    if ($trimmed === '') {
        return str_repeat('x', mb_strlen($str, 'UTF-8'));
    }
    $firstChar = mb_substr($trimmed, 0, 1, 'UTF-8');
    $remainingLength = mb_strlen($trimmed, 'UTF-8') - 1;
    return $firstChar . str_repeat('x', $remainingLength);
}

//新用户 锁定为老用户
function clockMember($member_id)
{
    $member_info = Db::name('member')->find($member_id);
    if ($member_info['is_clock'] == 0) {
        Db::name('member')->update([
            'id' => $member_id,
            'is_clock' => 1,
        ]);
    }
}

//升级成会员
function upMemberVip($order_data)
{
    $order_goods = Db::name('order_goods')->where([
        'order_id' => $order_data['id']
    ])->find();
    if ($order_goods) {
        $goods_up = Db::name('goods_up')->where([
            'goods_id' => $order_goods['goods_id']
        ])->find();
        if ($goods_up['is_dl'] == 1) {
            $member_info = Db::name('member')->find($order_data['member_id']);
            if ($member_info['level_id'] == 1) {
                setLevelMember($order_data['member_id'], 2);
            }
        }
    }
}

//1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货 7已取消 8待取货 9拼团待完成 10砍价发起
//支付299 成为会员
function upMemberVip2($order_data)
{
    //pay_money order_money
    $money = Db::name('order')->where([
        ['member_id', '=', $order_data['member_id']],
        ['status', 'in', [2, 3, 4, 5, 8]],
        ['pay_type', '=', 1],
        ['order_type', 'in', [2, 4]]
    ])->sum('order_money');
    $up_money = config('site.up_money') ? config('site.up_money') : 299;
    if ($money >= $up_money) {
        setLevelMember($order_data['member_id'], 2);
    }
}

function setLevelMember($member_id, $level_id)
{
    Db::name('member')->update([
        'id' => $member_id,
        'level_id' => $level_id,
    ]);
}

function InviteId($member_id)
{
//    $invite_id = 0;
//    $member_info = Db::name('member')->find($member_id);
//    if ($member_info['level_id'] >= 2) {
//        $invite_id = $member_id;
//    }
//    $invite_id = $member_id;
    return $member_id;
}

//给发起者返拼团卷
function returnPTToFQ($order_data)
{
    $group_activities_info = Db::name('group_activities')->find($order_data['activity_id']);
    $pin_money = $group_activities_info['group_price'];
    $group_num = $group_activities_info['group_num'];
    $coupons2 = $pin_money / ($group_num - 1);
    addPTCoupons($group_activities_info['member_id'], $coupons2, $order_data['id'], 5, '发起拼团奖励', $order_data['order_no']);
}

//拼团支付回调放到后面
function ptABFan($order_data)
{   //判断是第 1奇 2偶
    $count = Db::name('group_participants')->where([
        ['group_active_id', '=', $order_data['activity_id']],
        ['order_id', '<>', $order_data['id']],
        ['role', '=', 2],
    ])->count();
    $order_goods = Db::name('order_goods')
        ->where('order_id', $order_data['id'])
        ->find();
    $goods_info = Db::name('goods')->find($order_goods['goods_id']);
    if ($count % 2 == 0) {
        $return_rate = $goods_info['rate_a'];
    } else {

        $return_rate = $goods_info['rate_b'];
    }
    $group_participants_info = Db::name('group_participants')->where([
        ['role', '=', 1],
        ['group_active_id', '=', $order_data['activity_id']],
    ])->find();
    $money = round($order_data['order_money'] * ($return_rate / 100));
    reward1($group_participants_info['member_id'], $money, 2, $order_data['member_id'], $order_data);
    Db::name('');
}

//直推奖励 臻品区 健康区
function zhiTui($order_info)
{
    $member = Db::name('member')->find($order_info['member_id']);
    $invite_member = Db::name('member')->where([
        'id' => $member['invite_id']
    ])->find();
    if ($invite_member) {
        $order_goods_list = Db::name('order_goods')->where([
            'order_id' => $order_info['id']
        ])->column('goods_id');
        $goods_level_money = Db::name('goods_level_money')->where([
            ['goods_id', 'in', $order_goods_list],
            ['level_id', '=', $invite_member['level_id']]
        ])->select();
        foreach ($goods_level_money as $k => $v) {
            $order_goods = Db::name('order_goods')->where([
                'order_id' => $order_info['id'],
                'goods_id' => $v['goods_id']
            ])->find();
            $money = round($order_info['order_money'] * ($v['rate'] / 100), 2);
            if ($money > 0) {
                reward1($invite_member['id'], $money, 1, $order_info['member_id'], $order_info);
            }
        }
    }
}

//普通商品 团队奖励 平级奖励
function teamMoney($order_info)
{
    $Identity_info = getSuperiorShops($order_info['member_id']);
    $Identity_info2 = filterEntities($Identity_info);
    $data = array();
    if ($Identity_info2['small_shop']) {
        $data[] = $Identity_info2['small_shop'];
    }
    if ($Identity_info2['city_shop']) {
        $data[] = $Identity_info2['city_shop'];
    }
    if ($Identity_info2['director']) {
        $data[] = $Identity_info2['director'];
    }
    //1直推奖励 2拼团奖励 3团对奖励 4平级奖
    foreach ($data as $k => $v) {
        $money = round($order_info['order_money'] * ($v['team_rate'] / 100), 2);
        if ($money > 0) {
            reward1($v['id'], $money, 3, $order_info['member_id'], $order_info);
            //增加平级奖
            $member1 = Db::name('member')->find($v['id']);
            $member2 = Db::name('member')->find($member1['invite_id']);
            if ($member2 && ($member2['level_id'] == $member1['level_id'])) {
                $money2 = round($money / 10, 2);
                reward1($member2['id'], $money2, 4, $order_info['member_id'], $order_info);
            }
        }
    }
}

//拼团团队奖 平级奖励
function teamMoney2($order_info)
{
    $Identity_info = getSuperiorShops($order_info['member_id']);
    $Identity_info2 = filterEntities($Identity_info);

    $data = array();
    if ($Identity_info2['small_shop']) {
        $data[] = $Identity_info2['small_shop'];
    }
    if ($Identity_info2['city_shop']) {
        $data[] = $Identity_info2['city_shop'];
    }
    if ($Identity_info2['director']) {
        $data[] = $Identity_info2['director'];
    }
    //1直推奖励 2拼团奖励 3团对奖励 4平级奖
    foreach ($data as $k => $v) {
        $money = round($order_info['order_money'] * ($v['team_rate2'] / 100), 2);
        if ($money > 0) {
            reward1($v['id'], $money, 3, $order_info['member_id'], $order_info);
            //增加平级奖
            $member1 = Db::name('member')->find($v['id']);
            $member2 = Db::name('member')->find($member1['invite_id']);
            if ($member2 && ($member2['level_id'] == $member1['level_id'])) {
                $money2 = round($money / 10, 2);
                reward1($member2['id'], $money2, 4, $order_info['member_id'], $order_info);
            }
        }
    }
}

function dealTeam($Identity_info)
{
    $return = array();
    if (!is_null($Identity_info['director'])) {
        if ($Identity_info['director']['sort'] == 1) {
            $return[] = $Identity_info['director'];
            return $return;
        }
        if ($Identity_info['director']['sort'] == 2) {
            $return[] = $Identity_info['director'];
            if (!is_null($Identity_info['city_shop']) && $Identity_info['city_shop']['sort'] == 1) {
                $return[] = $Identity_info['city_shop'];
            }
            if (!is_null($Identity_info['small_shop']) && $Identity_info['small_shop']['sort'] == 1) {
                $return[] = $Identity_info['small_shop'];
            }
            return $return;
        }
        if ($Identity_info['director']['sort'] == 3) {
            $return[] = $Identity_info['director'];
            if (!is_null($Identity_info['city_shop'])) {
                $return[] = $Identity_info['city_shop'];
            }
            if (!is_null($Identity_info['small_shop']) && $Identity_info['small_shop']['sort'] == 1) {
                $return[] = $Identity_info['small_shop'];
            }
            return $return;
        }
    }
    if (!is_null($Identity_info['city_shop'])) {
        if ($Identity_info['city_shop']['sort'] == 1) {
            $return[] = $Identity_info['city_shop'];
            return $return;
        }
        if ($Identity_info['city_shop']['sort'] == 2) {
            $return[] = $Identity_info['city_shop'];
            if (!is_null($Identity_info['small_shop'])) {
                $return[] = $Identity_info['small_shop'];
            }
            return $return;
        }
    }
    if (!is_null($Identity_info['small_shop'])) {
        $return[] = $Identity_info['small_shop'];
        return $return;
    }
    return $return;
}

function filterEntities(array $data): array
{
    // 检查是否存在 director 且其 sort 值最小
    $directorSort = isset($data['director']['sort']) ? $data['director']['sort'] : PHP_INT_MAX;
    $cityShopSort = isset($data['city_shop']['sort']) ? $data['city_shop']['sort'] : PHP_INT_MAX;
    $smallShopSort = isset($data['small_shop']['sort']) ? $data['small_shop']['sort'] : PHP_INT_MAX;

    // 找出最小的 sort 值
    $minSort = min($directorSort, $cityShopSort, $smallShopSort);

    $result = [];

    if ($minSort === $directorSort && isset($data['director'])) {
        // 如果 director 的 sort 最小，则只保留 director
        $team_rate = Db::name('member_level')->where([
            ['id', 'in', [3, 4, 5]]
        ])->sum('team_rate');
        $team_rate2 = Db::name('member_level')->where([
            ['id', 'in', [3, 4, 5]]
        ])->sum('team_rate2');

        $result['director'] = $data['director'];
        $result['director']['team_rate'] = $team_rate;
        $result['director']['team_rate2'] = $team_rate2;
    } elseif ($minSort === $cityShopSort && isset($data['city_shop'])) {
        // 如果 city_shop 的 sort 最小，则保留 city_shop 和 director
        $result['city_shop'] = $data['city_shop'];
        $team_rate = Db::name('member_level')->where([
            ['id', 'in', [3, 4]]
        ])->sum('team_rate');
        $team_rate2 = Db::name('member_level')->where([
            ['id', 'in', [3, 4]]
        ])->sum('team_rate2');
        $result['city_shop']['team_rate'] = $team_rate;
        $result['city_shop']['team_rate2'] = $team_rate2;
        if (isset($data['director'])) {
            $member_level_director_info = Db::name('member_level')->find($data['director']['level_id']);
            $result['director'] = $data['director'];
            $result['director']['team_rate'] = $member_level_director_info['team_rate'];
            $result['director']['team_rate2'] = $member_level_director_info['team_rate2'];
        }
    } else {
        // 其他情况（small_shop 最小或相等时），保留所有存在的实体
        if (isset($data['small_shop'])) {
            $member_level_c1_info = Db::name('member_level')->find($data['small_shop']['level_id']);
            $result['small_shop'] = $data['small_shop'];
            $result['small_shop']['team_rate'] = $member_level_c1_info['team_rate'];
            $result['small_shop']['team_rate2'] = $member_level_c1_info['team_rate2'];
        }
        if (isset($data['city_shop'])) {
            $member_level_c2_info = Db::name('member_level')->find($data['city_shop']['level_id']);
            $result['city_shop'] = $data['city_shop'];
            $result['city_shop']['team_rate'] = $member_level_c2_info['team_rate'];
            $result['city_shop']['team_rate2'] = $member_level_c2_info['team_rate2'];
        }
        if (isset($data['director'])) {
            $member_level_c3_info = Db::name('member_level')->find($data['director']['level_id']);
            $result['director'] = $data['director'];
            $result['director']['team_rate'] = $member_level_c3_info['team_rate'];
            $result['director']['team_rate2'] = $member_level_c3_info['team_rate2'];
        }
    }
    if (isset($result['director']) && isset($result['small_shop']) && !isset($result['city_shop'])) {
        $team_rate = Db::name('member_level')->where([
            ['id', 'in', [4, 5]]
        ])->sum('team_rate');
        $team_rate2 = Db::name('member_level')->where([
            ['id', 'in', [4, 5]]
        ])->sum('team_rate2');
        $result['director'] = $data['director'];
        $result['director']['team_rate'] = $team_rate;
        $result['director']['team_rate2'] = $team_rate2;
    }

    return $result;
}

//上级最近的小店 市店 董事
function getSuperiorShops($userId)
{
    $result = [
        'small_shop' => null,  // 小店(level_id=3)
        'city_shop' => null,    // 市店(level_id=4)
        'director' => null,    // 董事(level_id=5)
    ];

    $currentLevel = 0; // 当前层级
    $sort = 1;
    // 从直接上级开始查找
    $inviteId = Db::name('member')->where('id', $userId)->value('invite_id');
    if ($userId == $inviteId) {
        return $result;
    }

    while ($inviteId) {
        $currentLevel++;

        // 获取上级用户信息
        $superior = Db::name('member')->where('id', $inviteId)
            ->field('id, level_id, invite_id')
            ->find();
        if ($superior['invite_id'] == $inviteId) {
            break;
        }

        if (!$superior) {
            break;
        }

        // 检查是否是需要的等级
        switch ($superior['level_id']) {
            case 3: // 小店
                if (is_null($result['small_shop']['id'])) {
                    $result['small_shop'] = [
                        'id' => $superior['id'],
//                        'top_level' => $currentLevel,
                        'level_id' => $superior['level_id'],
                        'sort' => $sort
                    ];
                }
                $sort++;
                break;
            case 4: // 市店
                if (is_null($result['city_shop']['id'])) {
                    $result['city_shop'] = [
                        'id' => $superior['id'],
//                        'top_level' => $currentLevel,
                        'level_id' => $superior['level_id'],
                        'sort' => $sort
                    ];
                    $sort++;
                }
                break;
            case 5: // 董事
                if (is_null($result['director']['id'])) {
                    $result['director'] = [
                        'id' => $superior['id'],
//                        'top_level' => $currentLevel,
                        'level_id' => $superior['level_id'],
                        'sort' => $sort
                    ];
                    $sort++;
                }
                break;
        }

        // 如果已经找到所有需要的等级，可以提前退出循环
        if (!is_null($result['small_shop']['id']) &&
            !is_null($result['city_shop']['id']) &&
            !is_null($result['director']['id'])) {
            break;
        }

        // 继续向上查找
        $inviteId = $superior['invite_id'];
    }

    return $result;
}

//获取最近上级
//输入用户id获取用户的服务中心 分公司 董事


// 增加待入账 1(直推)奖励 2拼团奖励 3团队奖励 4平级奖
function reward1($member_id, $money, $type, $junior_member_id, $order_info)
{
    $insert_date = array(
        'member_id' => $member_id,
        'money' => $money,
        'create_time' => time(),
        'junior_member_id' => $junior_member_id,
        'type' => $type,
        'status' => 0
    );
    switch ($type) {
        case 1:
            $insert_date['desc'] = '下单奖励';
            break;
        case 2:
            $insert_date['desc'] = '拼团奖励';
            break;
        case 3:
            $insert_date['desc'] = '团队奖励';
            break;
        case 4:
            $insert_date['desc'] = '平级奖';
            break;
        default:
            $insert_date['desc'] = '其它';
    }
    if ($order_info) {
        $insert_date['order_id'] = $order_info['id'];
        $insert_date['order_no'] = $order_info['order_no'];
        $order_goods = Db::name('order_goods')->where('order_id', $order_info['id'])->find();
        $insert_date['goods_id'] = $order_goods['goods_id'];
        $insert_date['goods_num'] = $order_goods['num'];
        $insert_date['goods_price'] = $order_goods['price'];
    }
    Db::name('reward')->insertGetId($insert_date);
}

//奖励金额到账
function getReward($order_info)
{
    $reward_list = Db::name('reward')->where([
        'order_id' => $order_info['id'],
        'status' => 0,
    ])->select();
    foreach ($reward_list as $k => $v) {
        addMoney($v['member_id'], $v['money'], $v['type'], $order_info);
        Db::name('reward')->update([
            'id' => $v['id'],
            'status' => 1,
        ]);
    }
}

//购物返购物卷
function addGWCouponsToOrder($order_info)
{
    $order_goods_info = Db::name('order_goods')->where([
        'order_id' => $order_info['id']
    ])->find();
    $goods_attr_value_info = Db::name('goods_attr_value')->where([
        'goods_id' => $order_goods_info['goods_id'],
        'suk' => $order_goods_info['suk'],
    ])->find();
    if ($goods_attr_value_info['r_coupons'] > 0) {
        //购物卷修改 1签到 2购物返现 3消费 4拼团卷兑换 5购物卷商城兑换 6订单取消返回
        $num = $order_goods_info['num'] * $goods_attr_value_info['r_coupons'];
        addGWCoupons($order_info['member_id'], $num, $order_info['id'], '', 2, '购物奖励');
    }

}

//1直推奖励 2拼团奖励 3团队奖励 4平级奖励 6提现
function addMoney($member_id, $money, $type, $order_info = null)
{
    $insert_data = array(
        'member_id' => $member_id,
        'money' => $money,
        'type' => $type,
        'create_time' => time()
    );
    switch ($type) {
        case 1:
            $insert_date['desc'] = '下单奖励';
            break;
        case 2:
            $insert_date['desc'] = '拼团奖励';
            break;
        case 3:
            $insert_date['desc'] = '团队奖励';
            break;
        case 4:
            $insert_date['desc'] = '平级奖';
            break;
        default:
            $insert_date['desc'] = '其它';
    }

    if ($order_info) {
        $insert_data['order_id'] = $order_info['id'];
        $insert_data['order_no'] = $order_info['order_no'];
    }
    if ($money > 0) {
        $insert_data['is_count'] = 1;
    } else {
        $insert_data['is_count'] = 2;
    }
    Db::name('member')->where(['id' => $member_id])->setInc('money', $money);
    $insert_id = Db::name('member_finance')->insertGetId($insert_data);
    return $insert_id;
}

//判断是否可升级小店
function isShop($member_id)
{
    //1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货
    //7已取消 8待取货 9拼团待完成10砍价发起
    $junior_ids = getTeamMembersRecursive($member_id);
    $team_money = Db::name('order')->where([
        ['member_id', 'in', $junior_ids],
        ['status', 'in', [4, 5]],
        ['pay_type', 'in', [1]],
    ])->sum('order_money');
    $group_count = Db::name('group_activities')->where([
        'member_id' => $member_id,
        'status' => 2
    ])->count();
    if ($team_money >= 10000 && $group_count >= 2) {
        return 1;
    }
    return -1;
}

//判断是否可升级市店 3小店 4市店 5董事
function isCityShop($member_id)
{
    //1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货
    //7已取消 8待取货 9拼团待完成 10砍价发起
    $junior_ids = getTeamMembersRecursive($member_id);
    $team_money = Db::name('order')->where([
        ['member_id', 'in', $junior_ids],
        ['status', 'in', [4, 5]],
        ['pay_type', 'in', [1]],
    ])->sum('order_money');
    //获取直属下级
    $zhi_junior_ids = Db::name('member')->where([
        'invite_id' => $member_id
    ])->column('id');
    $xdShop = 0;
    foreach ($zhi_junior_ids as $k => $v) {
        $c = getTeamMembersRecursive($v);
        $c_num = Db::name('member')->where([
            ['id', 'in', $c],
            ['level_id', 'in', [3, 4]],//包含小店 市店
        ])->count();
        if ($c_num > 0) {
            $xdShop++;
        }
    }
    if ($team_money >= 100000 && $xdShop >= 3) {
        return 1;
    }
    return 0;
}

//判断判断是否升级股东
function isDongshi($member_id)
{
    //1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货
    //7已取消 8待取货 9拼团待完成10砍价发起
    $junior_ids = getTeamMembersRecursive($member_id);
    $team_money = Db::name('order')->where([
        ['member_id', 'in', $junior_ids],
        ['status', 'in', [4, 5]],
        ['pay_type', 'in', [1]],
    ])->sum('order_money');

    //获取直属下级
    $zhi_junior_ids = Db::name('member')->where([
        'invite_id' => $member_id
    ])->column('id');
    $xdShop = 0;
    foreach ($zhi_junior_ids as $k => $v) {
        $c = getTeamMembersRecursive($v);
        $c_num = Db::name('member')->where([
            ['id', 'in', $c],
            ['level_id', 'in', [4]],//市店
        ])->count();
        if ($c_num > 0) {
            $xdShop++;
        }
    }
    if ($team_money >= 1000000 && $xdShop >= 4) {
        return 1;
    }
    return 0;
}


//输入id获取团队id 不包括本id
function getTeamMembersRecursive($userId)
{
    $teamMembers = [];
    // 查询当前用户直接邀请的用户
    $directMembers = Db::name('member')
        ->where('invite_id', $userId)
        ->column('id');

    // 将直接邀请的用户加入团队
    $teamMembers = array_merge($teamMembers, $directMembers);
    // 递归获取间接邀请的用户
    foreach ($directMembers as $memberId) {
        $teamMembers = array_merge($teamMembers, getTeamMembersRecursive($memberId));
    }
    return $teamMembers;
}

function queryExpress($key, $customer, $express_code, $express_no)
{
//    $key = $key;                        // 客户授权key
//    $customer = $customer;                   // 查询公司编号
    $param = array(
        'com' => $express_code,             // 快递公司编码
        'num' => $express_no,     // 快递单号
        'phone' => '',                // 手机号
        'from' => '',                 // 出发地城市
        'to' => '',                   // 目的地城市
        'resultv2' => '1',            // 开启行政区域解析
        'show' => '0',                // 返回格式：0：json格式（默认），1：xml，2：html，3：text
        'order' => 'desc'             // 返回结果排序:desc降序（默认）,asc 升序
    );
    $post_data = array();
    $post_data['customer'] = $customer;
    $post_data['param'] = json_encode($param, JSON_UNESCAPED_UNICODE);
    $sign = md5($post_data['param'] . $key . $post_data['customer']);
    $post_data['sign'] = strtoupper($sign);
    $url = 'https://poll.kuaidi100.com/poll/query.do';    // 实时查询请求地址
    $return_date = postUrl($url, $post_data);
    return $return_date;
}

function postUrl($url, $post_data)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $result = curl_exec($ch);
    // 第二个参数为true，表示格式化输出json
    $data = json_decode($result, true);
    return $data;
}

function getStrtoTime($time)
{
    $start_timestamp = strtotime("first day of $time 00:00:00");

// 获取该月最后一天的结束时间戳（23:59:59）
    $end_timestamp = strtotime("last day of $time 23:59:59");

    $data[] = $start_timestamp;
    $data[] = $end_timestamp;
    return $data;
}

//间隔天数
function getDaysDiff($send_time, $current_time = null)
{
    $current_time = $current_time ?? time();
    return abs(floor(($current_time - $send_time) / 86400));
}

//设置拼团上级
function setPinUp($order_data)
{
    $member_info = Db::name('member')->find($order_data['member_id']);
//    if ($member_info['is_clock'] == 1) {
//        return;
//    }
    $group_activities_info = Db::name('group_activities')->find($order_data['activity_id']);
    if ($group_activities_info) {
        Db::name('member')->update([
            'id' => $order_data['member_id'],
            'invite_id' => $group_activities_info['member_id'],
            'is_pin' => 2
        ]);
    }
}

//设置砍价上级
function setBargainUp($bargain_activity_id, $join_member_id)
{
    $member_info = Db::name('member')->find($join_member_id);
//    if ($member_info['is_clock'] == 1) {
//        return;
//    }
    $bargain_activity_info = Db::name('bargain_activity')->find($bargain_activity_id);
    if ($bargain_activity_info) {
        Db::name('member')->update([
            'id' => $join_member_id,
            'invite_id' => $bargain_activity_info['member_id'],
            'is_bargain' => 2
        ]);
    }
}

//这两天是否领取
function hasReceivedCouponRecently($member_id, $coupons_id)
{
    // 计算两天前的时间戳
    $twoDaysAgo = strtotime('-2 days');
    // 查询数据库
    $count = Db::name('member_coupons')
        ->where([
            'member_id' => $member_id,
            'coupon_id' => $coupons_id
        ])
        ->where('create_time', '>=', $twoDaysAgo)
        ->count();
    return $count > 0;
}

//输入时间戳 获取每年每月
function generateYearMonthArray($timestamp, $endTimestamp = null)
{
    $start = new DateTime("@$timestamp");
    $start->setTime(0, 0, 0); // 时间归零，避免时区影响
    $start->modify('first day of this month'); // 从当月1日开始

    $end = $endTimestamp ? new DateTime("@$endTimestamp") : new DateTime();
    $end->modify('first day of this month'); // 结束时间也取当月1日

    $interval = new DateInterval('P1M'); // 按月递增
    $period = new DatePeriod($start, $interval, $end);

    $result = [];
    foreach ($period as $date) {
        $result[] = $date->format('Y-m');
    }

    return $result;
}

//总团队业绩
function teamMoneySum($member_id)
{
    $teamMembers = getTeamMembersRecursive($member_id);
    array_unshift($teamMembers, $member_id);//在团队中加入自己
    $money = getEffectOrderMoneySum($teamMembers);
    return $money;
}

function getEffectOrderMoneySum($member_ids)
{
    //1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货
    //7已取消 8待取货 9拼团待完成 10砍价发起
    $money = Db::name('order')->where([
        ['member_id', 'in', $member_ids],
//        ['status', 'in', [2,3,8,4, 5]],
        ['status', 'in', [4, 5]],
        ['pay_type', '=', 1]
    ])->sum('pay_money');
    return $money;
}

function getEffectOrderMoney($member_ids, $startTimestamp, $endTimestamp)
{
    $money = Db::name('order')->where([
        ['member_id', 'in', $member_ids],
        ['status', 'in', [4, 5]],
        ['pay_type', '=', 1],
        ['finish_time', 'between', [$startTimestamp, $endTimestamp]],
    ])->sum('order_money');
    return $money;
}

//升级是否可以发起助力订单
function upCreateZl($order_info)
{
    $order_goods = Db::name('order_goods')
        ->where('order_id', '=', $order_info['id'])
        ->find();
    $goods = Db::name('goods')->find($order_goods['goods_id']);
    if ($goods['is_can_zl'] == 1) {
        Db::name('member')->update([
            'id' => $order_info['member_id'],
            'is_create_zl' => 1
        ]);
    }
}

//创建代理奖励
function dlReward($order_info)
{
    $member_dl = Db::name('member_dl')->where([
        ['area', '=', $order_info['area']],
        ['is_del', '=', 0]
    ])->find();
    if ($member_dl) {
        //获取订单商品
        $order_goods = Db::name('order_goods')->where('order_id', '=', $order_info['id'])->find();
        $goods_info = Db::name('goods')->find($order_goods['goods_id']);
        $money = round(($order_info['order_money'] * $goods_info['dl_rate']) / 100, 2);
        if ($money > 0) {
            reward1($member_dl['member_id'], $money, 1, $order_info['member_id'], $order_info);
        }
    }
}

//会员订单返回积分
function dayJf($order_info)
{
    if ($order_info['order_type'] == 3) {
        //获取商品购买属性
        $order_goods = Db::name('order_goods')
            ->where('order_id', '=', $order_info['id'])
            ->find();
        //获取每日获取积分
        $goods_attr_value = Db::name('goods_attr_value')->where([
            'goods_id' => $order_goods['goods_id'],
            'suk' => $order_goods['suk'],
        ])->find();

        if ($goods_attr_value['one_day_jf'] > 0) {
            $one_yuan_jf = config('site.one_yuan_jf') ? config('site.one_yuan_jf') : 100;
            $goods_money = $order_goods['sum_money'];
            //所有返回积分
            $sum_jf = $goods_money * $one_yuan_jf;


            //day_num
            $day_num = ceil($sum_jf / $goods_attr_value['one_day_jf']);

            $ojr = array(
                'order_id' => $order_info['id'],
                'member_id' => $order_info['member_id'],
                'create_time' => time(),
                'day_num' => $day_num,
                'day_jf' => $goods_attr_value['one_day_jf'],
                'sum_jf' => $sum_jf
            );
            $ojr_id = Db::name('order_jf_return')->insertGetId($ojr);

            //todo 设置消息队列
            $order_jf_return_detail = generateDailyPointsRecord($sum_jf, $goods_attr_value['one_day_jf'], $ojr_id, $order_info['member_id'], $order_info['id']);
            Db::name('order_jf_return_detail')->insertAll($order_jf_return_detail);
        }
    }
}

/**
 * 生成每日积分领取记录数组
 *
 * @param int $sum 总积分
 * @param int $num 每天可领取积分
 * @param string $startDate 开始日期，默认为今天
 * @return array 每日领取记录数组，包含时间戳信息
 * 订单完成时间作为 $startDate
 */
function generateDailyPointsRecord($sum, $num, $ojrid, $member_id, $order_id, $startDate = 'today')
{
    // 验证输入参数
    if ($sum <= 0 || $num <= 0) {
        throw new InvalidArgumentException('总积分和每天积分必须大于0');
    }

    if ($num > $sum) {
        throw new InvalidArgumentException('每天积分不能大于总积分');
    }

    // 计算需要多少天
    $days = ceil($sum / $num);

    // 创建开始日期的时间对象
    $startDateTime = new DateTime($startDate);
    $startDateTime->setTime(0, 0, 0); // 设置为当天的开始时间

    $records = [];
    $remainingPoints = $sum;

    for ($i = 0; $i < $days; $i++) {
        $currentDate = clone $startDateTime;
        $currentDate->modify("+$i days");

        // 计算当天实际可领取的积分
        $dailyPoints = min($num, $remainingPoints);
        $remainingPoints -= $dailyPoints;

        // 生成时间戳范围（当天00:00:00到23:59:59）
        $startTimestamp = $currentDate->getTimestamp();
        $endDate = clone $currentDate;
        $endDate->setTime(23, 59, 59);
        $endTimestamp = $endDate->getTimestamp();
        $records[] = [
            'ojrid' => $ojrid,
            'member_id' => $member_id,
            'day' => $i + 1,
            'date' => $currentDate->format('Y-m-d'),
            'points' => $dailyPoints,
            'start_timestamp' => $startTimestamp,
            'end_timestamp' => $endTimestamp,
            'start_time' => $currentDate->format('Y-m-d H:i:s'),
            'end_time' => $endDate->format('Y-m-d H:i:s'),
            'create_time' => time(),
            'order_id' => $order_id
        ];
        if ($remainingPoints <= 0) {
            break;
        }
    }
    return $records;
}

function setGetJf($order_id)
{
    $now_time = time();
    $where[] = ['order_id', '=', $order_id];
    $where[] = ['is_get', '=', 0];
    $where[] = ['end_timestamp', '<', $now_time];
    Db::name('order_jf_return_detail')->where($where)->update([
        'is_get' => 2
    ]);
    //获取最新 获取当天时间是否大于 如果是 设置完成领取
    //todo 测试
    $last_day = Db::name('order_jf_return_detail')
        ->where([
            ['order_id', '=', $order_id],
        ])->order('day desc')->find();
    if ($last_day['end_timestamp'] < time()) {
        Db::name('order_jf_return')->where([
            ['order_id', '=', $order_id]
        ])->update([
            'status' => 1,
        ]);
    }
}

//会员订单奖励分享的人返积分
//订单完成后发送
function returnfxOrder($order_info)
{
    //是不是会员订单
    if ($order_info['order_type'] != 3) {
        return;
    }
    //判断分享用户之前是否有有效订单
    $isBuyGoods = isBuyGoods($order_info);
    if ($isBuyGoods && $order_info['fx_member_id']) {
        $goods_info = Db::name('goods')->find($isBuyGoods['goods_id']);
        //商品返现比例
        if ($goods_info['hy_rate'] > 0) {
            //订单金额
            $one_yuan_jf = config('site.one_yuan_jf') ? config('site.one_yuan_jf') : 100;
            $return_jf = $order_info['order_money'] * ($goods_info['hy_rate'] / 100) * $one_yuan_jf;
            Db::name('order')->update([
                'id' => $order_info['id'],
                'fx_get_jf' => $return_jf
            ]);
            if ($return_jf > 0) {
                addGWCoupons2($order_info['fx_member_id'], $return_jf, 1, $order_info['id'], 6);
            }
        }
    }

}

//1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货
//7已取消 8待取货 9助力中 10砍价发起
function isBuyGoods($order_info)
{
    $order_goods = Db::name('order_goods')->where([
        'order_id' => $order_info['id']
    ])->find();
    $where[] = ['o.member_id', '=', $order_info['fx_member_id']];
    $where[] = ['o.status', 'in', [2, 3, 4, 5]];
    $where[] = ['og.goods_id', '=', $order_goods['goods_id']];
    $order_info = Db::name('order')
        ->alias('o')
        ->field('o.*,og.goods_id')
        ->join('order_goods og', 'og.order_id=o.id')
        ->where($where)
        ->find();
    if ($order_info) {
        return $order_info;
    } else {
        return 0;
    }
}

//30 的取余
function mapNumberToRange($number)
{
    // 处理0和负数的情况
    if ($number <= 0) {
        return 1;
    }

    // 使用取模运算
    $result = $number % 30;

    // 如果余数为0，显示30；否则显示余数
    return $result === 0 ? 30 : $result;
}
function getAccessToken2()
{
    $appid = config('wechat.appID');
    $secret = config('wechat.AppSecret');
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
    $result = json_decode(file_get_contents($url), true);
    return $result['access_token'];
}
//小程序发货
function uploadShippingInfo($order_info)
{
    $access_token = getAccessToken2();
    $member_info = Db::name('member')->find($order_info['member_id']);
    $order_goods=Db::name('order_goods')->where('order_id','=',$order_info['id'])->find();
    $config = config('wechat.wxpay');
    //todo 总结小程序发货
    $shipping_data = [
        'order_key' => [
            'order_number_type' => 2, // 1-微信订单号，2-商户订单号
//                'out_trade_no' => '4200002830202508041965204260',
            'transaction_id' => $order_info['transaction_id'],
            'mchid' => '1726357128',
        ],
        'logistics_type' => 3, // 1、实体物流配送采用快递公司进行实体物流配送形式 2、同城配送 3、虚拟商品，虚拟商品，例如话费充值，点卡等，无实体配送形式 4、用户自提
        'delivery_mode' => 1,
        'shipping_list' => [
            [
//                    'tracking_no' => $order_info['express_no'],
//                    'express_company' => $express_info['code2'],
//                'express_company' => '',
//                'shipping_company_name' => '物流公司名称（如顺丰）',
                'item_desc' => $order_goods['goods_name']
            ]
        ],
        'upload_time' => date('Y-m-d\TH:i:sP'), // 时间戳
        //'upload_time' => "2024-10-18T16:50:27+08:00", // 时间戳
        'payer' => [
            'openid' => $member_info['openid']
        ]
    ];


    // 微信API地址
    $url = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token={$access_token}";

    // 转换为JSON
    $json_data = json_encode($shipping_data, JSON_UNESCAPED_UNICODE);

//    dump($json_data);
//    die;

    // 初始化CURL
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Content-Length: ' . strlen($json_data)
    ]);

    // 执行请求
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    // 解析响应
    $result = json_decode($response, true);

    if ($http_code !== 200 || !$result) {
        return $result;
    }

    if (isset($result['errcode']) && $result['errcode'] != 0) {
        return $result;
    }

//    Db::name('order')->update([
//        'id' => $order_info['id'],
//        'is_fa' => 1,
//        'fa_time' => time()
//    ]);

    return $result;
}

//判断是否代理
function isDl($member_id)
{
    $is_dl = Db::name('member_dl')->where([
        'is_del' => 0,
        'member_id' => $member_id
    ])->find();
    if ($is_dl) {
        return 1;
    }
    return 0;
}















